package com.wuda.servlet.admin;

import com.wuda.bean.User;
import com.wuda.dao.UserDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@WebServlet("/admin/getAllUser")
public class GetAllUser extends HttpServlet {
	UserDao userDao = new UserDao();

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json; charset=utf8");
		PrintWriter out = response.getWriter();

		String limitStr = request.getParameter("limit");
		String pageStr = request.getParameter("page");
		String username = request.getParameter("username");

		int limit = (limitStr != null) ? Integer.parseInt(limitStr) : 10;
		int page = (pageStr != null) ? Integer.parseInt(pageStr) : 1;
		int offset = (page - 1) * limit;

		HashMap<String, Object> hashMap = new HashMap<>();

		try {
			List<User> users = userDao.getAllUsers(username, limit, offset);
			int count = userDao.getUserCount(username);

			if (!users.isEmpty()) {
				hashMap.put("code", 200);
				hashMap.put("msg", "查询成功");
				hashMap.put("count", count);
				JSONArray jsonArray = new JSONArray();
				for (User user : users) {
					JSONObject jsonData = new JSONObject();
					jsonData.put("user_id", user.getUserId());
					jsonData.put("username", user.getUsername());
					jsonData.put("email", user.getEmail());
					jsonData.put("role", user.getRole());
					jsonData.put("status", user.getStatus());

					jsonArray.add(jsonData);
				}
				hashMap.put("data", jsonArray);
			} else {
				hashMap.put("code", 201);
				hashMap.put("msg", "无数据");
			}
		} catch (Exception e) {
			hashMap.put("code", 500);
			hashMap.put("msg", "数据库操作错误");
			e.printStackTrace();
		}

		JSONObject json = JSONObject.fromObject(hashMap);
		out.write(json.toString());
	}

}
